package org.smart4j.framework.helper;

import org.apache.commons.dbcp2.BasicDataSource;
import org.apache.commons.dbutils.QueryRunner;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.smart4j.framework.util.DBUtil;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.Properties;

/**
 * 数据库操作助手类
 *
 * Created by chinalin on 2017/3/23.
 */
public final class DatabaseHelper {
    private static final Logger LOGGER = LoggerFactory.getLogger(DatabaseHelper.class);

    /**
     * 开启事务
     */
    public static void beginTransaction(){
        try {
            Connection conn = DBUtil.getConnection();
            if (conn != null){
                conn.setAutoCommit(false);      //不自动提交事务
            }
        } catch (SQLException e){
            LOGGER.error("begin transaction failure" , e);
            throw new RuntimeException(e) ;
        }finally {
            //加入线程池中的连接-->在DBUtil中已经做了。
        }
    }

    /**
     *提交事务
     */
    public static void commitTransaction(){
        try {
            Connection conn = DBUtil.getConnection() ;
            if (conn != null){
                conn.commit();
                DBUtil.closeConnection();
            }
        }catch (SQLException e){
            LOGGER.error("commit transaction failure ",e );
            throw new RuntimeException(e) ;
        }finally {
            //移除线程池中的连接-->在DBUtil中已经做了。
        }
    }

    /**
     * 回滚事务
     */
    public static void rollbackTransaction(){
        try {
            Connection conn = DBUtil.getConnection();
            if (conn != null) {
                conn.rollback();
                conn.close();
            }
        }catch (SQLException e){
            LOGGER.error("rollback transaction failure ",e );
            throw new RuntimeException(e) ;
        }finally {
            //移除线程池中的连接-->在DBUtil中已经做了。
        }
    }
}
